<template>
  <div class="users-container" >
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 下侧用户列表 -->
     <div class="users-list">
        <!-- 上侧搜索框 -->
        <div>
          <el-input placeholder="请输入内容" v-model.trim="input" class="search-input">
              <el-button @click="queryUsersId" slot="append" icon="el-icon-search"></el-button>
          </el-input>
           <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
           <!-- 添加用户弹出框 -->
           <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px" class="demo-ruleForm">
             <el-form-item label="用户" prop="username">
                  <el-input maxlength="6" v-model.trim="ruleForm.username"></el-input>
             </el-form-item>
             <el-form-item  label="密码" prop="password">
                  <el-input v-model.trim="ruleForm.password"></el-input>
             </el-form-item>
             <el-form-item label="邮箱" prop="email">
                  <el-input v-model.trim="ruleForm.email"></el-input>
             </el-form-item>
             <el-form-item label="手机" prop="mobile">
                  <el-input maxlength="11" v-model.trim="ruleForm.mobile"></el-input>
             </el-form-item>
            </el-form>
          <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUsers">确 定</el-button>
         </div>
       </el-dialog>
       </div>
       <!-- table表格 -->
            <el-table
               :data="tableData"
               border
               style="width: 100%">
                <el-table-column prop="id"  label="#"></el-table-column>
                <el-table-column prop="username"  label="姓名" ></el-table-column>
                <el-table-column prop="email"  label="邮箱"></el-table-column>
                <el-table-column prop="mobile"  label="电话" ></el-table-column>
                <el-table-column prop="role_name"  label="角色" ></el-table-column>
                <!-- 状态作用域插槽 -->
                <el-table-column  label="状态" >
                    <template slot-scope="scope">
                        <el-switch
                          @change="changeNowStatus(scope.row.id,scope.row.mg_state)"
                          v-model="scope.row.mg_state">
                        </el-switch>
                    </template>
                </el-table-column>
                 <!-- 操作作用域插槽 -->
                 <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button
                     class="operate-btn"
                      size="mini"
                      type="primary"
                      @click="handleEdit(scope.row)">
                      <i class="el-icon-edit"></i>
                      </el-button>
                    <!-- 编辑弹出框 -->
                      <el-dialog title="修改用户"  :visible.sync="dialogEdit">
                          <el-form :model="EditForm" status-icon :rules="rules"  label-width="70px">
                            <el-form-item label="用户" prop="username">
                              <el-input  :disabled="true"  v-model.trim="EditForm.username" autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item label="邮箱" prop="email">
                              <el-input  v-model.trim="EditForm.email" autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item label="手机号" prop="mobile">
                              <el-input  v-model.trim="EditForm.mobile" autocomplete="off"></el-input>
                            </el-form-item>
                           </el-form>
                        <div slot="footer" class="dialog-footer">
                          <el-button @click="dialogEdit = false">取 消</el-button>
                          <el-button  type="primary" @click="editUsers(Editid)" >确 定</el-button>
                        </div>
                      </el-dialog>
                    <el-button
                    class="operate-btn"
                      size="mini"
                      type="danger"
                      @click="handleDelete(scope.row)">
                      <i class=" el-icon-delete"></i>
                      </el-button>
                    <el-button
                    class="operate-btn"
                      size="mini"
                      type="warning"
                      @click="handleAssign(scope.row)">
                      <i class="el-icon-setting"></i>
                      </el-button>
                      <!-- 分配角色弹框 -->
                      <el-dialog title="分配新角色" :visible.sync="dialogForm">
                          <el-form>
                            <el-form-item label="当前的用户：">
                             {{formAss.nowuser}}
                            </el-form-item>
                              <el-form-item label="当前的角色：">
                               {{formAss.nowRole}}
                              </el-form-item>
                            <el-form-item label="分配新角色：" >
                               <el-select v-model="values" placeholder="请选择">
                                <el-option v-for="item in form" :key="item.roleName" :label="item.roleName" :value="item.roleName"></el-option>
                            </el-select>
                          </el-form-item>
                          </el-form>
                          <div slot="footer" class="dialog-footer">
                            <el-button @click="dialogForm = false">取 消</el-button>
                            <el-button type="primary" @click="changeAssignRole">确 定</el-button>
                          </div>
                      </el-dialog>
                  </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="block">
                  <el-pagination
                    :current-page="currentPage"
                    @current-change="currentChange"
                    :page-sizes="[2, 4, 6, 8]"
                    :page-size="currentNum"
                    @size-change='currentSize'
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageNumber.total">
                  </el-pagination>
            </div>
     </div>
  </div>
</template>

<script>
//
import { getUsersList, addUser, getNewStatus, queryUSerInfo, editUSerInfo, deleteUSer, userRoleList, assignUserRole } from '@/api/user.js'
const mobileReg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
export default {
  name: 'users',
  data () {
    return {
      // 输入框内容
      input: '',
      // 表格数据
      tableData: [],
      // 转换开关
      value: true,
      // 页数
      pageNumber: {},
      // 前往几页
      currentPage: 1,
      // 每页几条
      currentNum: 2,
      // 控制添加用户弹出框出现和隐藏
      dialogFormVisible: false,
      // 表单数据
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 表单校验
      rules: {
        username: [
          { required: true, message: '请输入用户名' },
          { pattern: /^[a-z0-9]+$/i, message: '只能输入英文和数字' }
        ],
        password: [
          { required: true, message: '请输入密码' },
          { pattern: /^\w+$/, message: '只能输入英文和数字和下划线' }
        ],
        email: [
          { required: true, message: '请输入邮箱' },
          { pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, message: '请输入正确邮箱格式' }
        ],
        mobile: [
          { required: true, message: '请输入手机' },
          { pattern: mobileReg, message: '请输入正确手机号' }
        ]
      },
      // 编辑弹出框
      dialogEdit: false,
      // 编辑id
      Editid: null,
      // 编辑表格数据
      EditForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 分配角色弹出框
      dialogForm: false,
      // 分配角色框数据
      form: [],
      // 分配角色弹出框数据
      formAss: {
        nowuser: '',
        nowRole: ''
      },
      // 下拉框默认值
      values: '',
      // 分配用户id
      assignId: '',
      // 分配角色id
      assignRoleId: ''
    }
  },
  created () {
    this.loadUsersList()
  },
  methods: {
  //  获取用户数据
    async loadUsersList () {
      try {
        const { data: res } = await getUsersList({
          query: this.input,
          pagenum: this.currentPage,
          pagesize: this.currentNum
        })
        // 页数
        this.pageNumber = res.data
        // 页面数据
        this.tableData = res.data.users
      } catch (err) {
        this.$message.error('获取失败')
      }
    },
    // 操作作用域插槽
    // 编辑
    async handleEdit (row) {
      this.dialogEdit = true
      this.EditForm.username = row.username
      this.EditForm.email = row.email
      this.EditForm.mobile = row.mobile
      this.Editid = row.id
      await queryUSerInfo(this.Editid)
    },
    // 删除
    handleDelete (row) {
      this.open(row.id)
    },
    // 分配新角色
    async  handleAssign (row) {
      this.formAss.nowuser = row.username
      this.formAss.nowRole = row.role_name
      this.assignId = row.id
      const { data } = await queryUSerInfo(this.assignId)
      this.assignRoleId = data.data.rid
      // 获得角色列表
      const { data: res } = await userRoleList()
      this.form = res.data
      this.dialogForm = true
    },
    // 页码改变是发起请求渲染页面
    currentChange (val) {
      // 赋值页码
      this.currentPage = val
      // 然后在请求数据
      this.loadUsersList()
    },
    // 条数改变
    currentSize (val) {
      this.currentNum = val
      this.loadUsersList()
    },
    // 添加用户
    async addUsers () {
      try {
        // 发起添加用户的请求
        const { data: res } = await addUser(this.ruleForm)
        // console.log(res.data.data)
        if (res.meta && res.meta.status === 400) {
          return this.$message({
            showClose: true,
            message: '不能为空',
            type: 'error'
          })
        }
        // 然后在请求最新的数据
        this.loadUsersList()
        this.$message({
          showClose: true,
          message: '添加成功',
          type: 'success'
        })
        this.$message.close()
      } catch (err) {
        this.$message({
          showClose: true,
          message: '添加失败',
          type: 'error'
        })
      }
      // 把弹出框关闭
      this.dialogFormVisible = false
    },
    // 修改用户状态
    async changeNowStatus (id, status) {
      try {
        //  修改用户状态
        await getNewStatus(id, status)
        // 重新获取页面数据
        this.loadUsersList()
        this.$message({
          showClose: true,
          message: '修改成功',
          type: 'success'
        })
      } catch (err) {
        this.$message({
          showClose: true,
          message: '修改失败',
          type: 'error'
        })
      }
    },
    // 查询用户
    async queryUsersId () {
      if (this.input === '') {
        return this.$message({
          showClose: true,
          message: '请输入内容',
          type: 'error'
        })
      }
      try {
        this.loadUsersList()
        // const { data: res } = await queryUSerInfo(username)
        // this.tableData = [res.data]
        // // 页数
        // this.pageNumber = { total: 1 }
        this.$message({
          showClose: true,
          message: '搜索成功',
          type: 'success'
        })
        this.input = ''
      } catch (err) {
        this.$message({
          showClose: true,
          message: '搜索失败',
          type: 'error'
        })
      }
    },
    // 编辑用户
    async editUsers (id) {
      const res = await editUSerInfo(id, {
        email: this.EditForm.email,
        mobile: this.EditForm.mobile
      })
      if (res.status === 200) {
        this.loadUsersList()
        this.$message({
          showClose: true,
          message: '编辑成功',
          type: 'success'
        })
      } else if (res.status === 500) {
        this.$message({
          showClose: true,
          message: '编辑失败',
          type: 'error'
        })
      }
      this.dialogEdit = false
    },
    // 删除弹框
    open (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 点击确定
        await deleteUSer(id)
        this.loadUsersList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 分配用户新角色
    async changeAssignRole () {
      // 发起分配新角色请求
      const { data: res } = await assignUserRole(this.assignRoleId, this.assignId)
      if (res.meta && res.meta.status === 400) {
        this.$message({
          type: 'error',
          message: '分配失败!'
        })
      } else {
        this.$message({
          type: 'success',
          message: '分配成功!'
        })
      }
      // 关闭弹框
      this.dialogForm = false
    }
  }
}
</script>

<style scoped lang="less">
.users-container{
  height: 100vh;
 background-color: #eaedf1;
 padding: 20px;
//  面包屑
 .el-breadcrumb{
   margin: 0;
 }
//  用户列表盒子
 .users-list{
   background-color: #fff;
   margin: 20px 20px 0 0;
   padding: 20px;
   box-shadow: #999;
   .search-input{
     width: 360px;
     height: 40px;
     margin: 0 15px;
   }
  //  table表格下的操作按钮
  /deep/.el-table .cell{
    padding-right: 0;
  }
  /deep/.operate-btn{
    width: 40px;
    height: 28px;
    font-size: 12px;
    padding: 5px 10px;
    margin: 3px;
  }
 }
}
</style>
